Rust 對於可靠性的做法,不只是避免錯誤;它是一種 有意識設計的哲學。它將每一種潛在失敗分為兩個領域: 可恢復的 和 不可恢復的 錯誤。這確保系統具備韌性、可預測性,並免於靜默的資料損壞。
1. 失敗的分類
一種 可恢復的錯誤 (例如檔案遺失) 是一個預期的障礙,程式可以嘗試重新執行或通知使用者。而一種 不可恢復的錯誤 (例如緩衝區溢位) 代表邏輯上的崩潰,最安全的做法是立即停止——即 快速失敗 原則。
2. 契約導向的開發
可靠性是透過明確的界線來達成的。如果一個函式的先決條件已滿足,但外部因素導致失敗,就回傳一個 Result。如果內部邏輯違反了核心不變量,Rust 會強制中止,以防止對系統狀態造成進一步損害。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Which of the following best describes a 'recoverable error' in Rust?
A total breakdown of logic where the program must halt.
An expected situation, such as a missing file, that the program can handle.
A memory leak that is automatically fixed by the compiler.
An error that only occurs in debug mode.
✅ Correct!
Correct! Recoverable errors are anticipated events where the code can take corrective action.❌ Incorrect
Think of errors like a 'File Not Found'—the program doesn't need to crash; it can just ask the user for a different file.QUESTION 2
What is the primary purpose of an 'unrecoverable error' (panic)?
To notify the user that their password was incorrect.
To stop execution immediately when a bug or contract violation is detected.
To provide a way for the program to retry a network request.
To optimize the code for better performance.
✅ Correct!
Exactly. Rust uses panics to 'Fail Fast' and prevent corrupted states from causing further harm.❌ Incorrect
Panics are for bugs and impossible states, not for routine user input issues.QUESTION 3
Why does Rust prefer explicit error handling over exceptions?
To make the code harder to read for security.
To prevent 'silent failures' that lead to corrupted states or vulnerabilities.
Because Rust does not have a stack to bubble up errors.
To allow the program to ignore errors completely.
✅ Correct!
Rust forces you to acknowledge potential failure points at design time, ensuring state integrity.❌ Incorrect
Exceptions often bubble up invisibly; Rust makes the possibility of failure a part of the function's type signature.QUESTION 4
If a function receives input that violates its core invariants (a bug), it should:
Return a Result::Err.
Panic to signal a logic error.
Ignore the input and return a default value.
Print a warning and continue.
✅ Correct!
Correct. If the program enters a state that should be impossible, halting is the safest path.❌ Incorrect
Return a Result for expected failures. If the logic itself is broken, that is a panic-worthy event.QUESTION 5
Which Rust type is used to represent a recoverable failure?
Option<T>
Result<T, E>
panic!
Box<dyn Error>
✅ Correct!
The Result enum explicitly encodes either success (Ok) or a handled failure (Err).❌ Incorrect
The panic! macro is for unrecoverable failures; Result is the container for recoverable ones.Case Study: The Resilient Web Server
Applying error philosophy to system design
You are designing a high-traffic web server. You must decide how to handle two distinct scenarios: 1) A user providing an invalid API key, and 2) The server detecting that its internal routing table has been corrupted by a memory-unsafe operation in a linked C-library.
Q
1. How should the 'Invalid API Key' scenario be handled and why?
Solution:
This should be a recoverable error returned via a
This should be a recoverable error returned via a
Result. It is an expected part of operation; the server should return a 401 status code and continue serving other requests.Q
2. How should the 'Corrupted Routing Table' scenario be handled and why?
Solution:
This must be an unrecoverable error triggering a
This must be an unrecoverable error triggering a
panic!. Since the internal state is corrupt, continuing to process transactions could lead to severe security leaks or data loss. Failing fast is the safest choice.